package com.glory.dgcpcpda.activity.mfg;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.CpcMaterialInfoEntity;
import com.glory.dgcpcpda.entity.MLotListEntity;
import com.glory.dgcpcpda.entity.MaterielListEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MaterielDownActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.tvMaterielLot)
    TextView tvMaterielLot;
    @BindView(R.id.ivMaterielLotArrow)
    ImageView ivMaterielLotArrow;
    @BindView(R.id.flMaterielLotList)
    FrameLayout flMaterielLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.spin_scapCode)
    Spinner spin_scapCode;
    @BindView(R.id.scapCodeLayout)
    LinearLayout scapCodeLayout;
    private List<String> materielLotList;
    private List<String> scrapList;
    private FreeUI_GeneralPop gearPop;
    private ArrayAdapter<String> adapter;
    private String scrapCode;
    private String scrapReason;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_materiel_down;
    }

    @Override
    protected void initView() {
        tvTitle.setText("物料Kittng下机");
        //checkBox.setVisibility(View.VISIBLE);
        checkBox.setChecked(true);
        setMainLayout(llMain);
        materielLotList = new ArrayList<>();


        String eqpid = getIntent().getExtras().getString("EQPID");
        String mlotId = getIntent().getExtras().getString("MLOTID");
        if (eqpid != null){
            etEqpWork.setText(eqpid);
            requestMaterialList(eqpid);
        }
        if (mlotId !=null){
            tvMaterielLot.setText(mlotId);
        }
        if(!tvMaterielLot.getText().toString().equals("")){
            requestMaterialInfo(tvMaterielLot.getText().toString());
        }

        tvMaterielLot.addTextChangedListener(new TextWatcher(){

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                System.out.println("beforeTextChanged:"+s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                System.out.println("onTextChanged:"+s);
                if(checkBox.isChecked()) {

                    requestMaterialInfo(s.toString());

                }
            }

            @Override
            public void afterTextChanged(Editable s) {System.out.println("afterTextChanged:"+s);}

        });

        initEdit(etEqpWork, s -> requestMaterialList(s));

    }

    private void requestMaterialList(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    materielLotList.clear();
                    List<MaterielListEntity.Materiel> mlotlist = response.body().getResponse().getBody().getMLOTLIST();
                    for (MaterielListEntity.Materiel materiel : mlotlist){
                        materielLotList.add(materiel.getMLOTID());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"MLOTKITTING");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","LOAD");
        map.addProperty("EQUIPMENTID",s);
        NetUtils.requestPostNet("MES.MLOTKITTING","MLOTKITTING",this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flMaterielLotList,R.id.checkbox})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit13")) {
//                    return;
//                }

                if (tvMaterielLot.getText().toString().equals("")){
                    showToast("请选择物料批号",false);
                    return;
                }
                if(checkBox.isChecked()){

                    if("".equals(spin_scapCode.getSelectedItem().toString())){
                        showToast("请选择下机原因！",false);
                        return;
                    }else{
                        scrapCode=spin_scapCode.getSelectedItem().toString().split("/")[0];
                        scrapReason=spin_scapCode.getSelectedItem().toString().split("/")[1];
                    }
                }else{
                    scrapCode="";
                    scrapReason="";
                }
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                                (new TypeToken<BaseResponseBean<JSONObject>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    showToast("物料下机成功", true);
                                    MaterielDownActivity.this.finish();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                                super.onError(response);
                                loadError(response.getException(),"MLOTKITTING");
                            }
                        };
                        JsonObject map = new JsonObject();
                        map.addProperty("ACTIONTYPE", "DEASSIGN");
                        map.addProperty("EQUIPMENTID", getText(etEqpWork));
//                        map.addProperty("TOWAREHOUSEID", "WareHouse");
                        MLotListEntity mLotListEntity = new MLotListEntity(tvMaterielLot.getText().toString(),"");
//


                        Map<String,String> mapScrapCode=new HashMap<>();
                        mLotListEntity.getUDF().put("actionCode",scrapCode);
                        mLotListEntity.getUDF().put("actionComment","");
                        mLotListEntity.getUDF().put("actionReason",scrapReason);


                        mLotListEntity.setEQUIPMENTID(getText(etEqpWork));
                        String state="";
                        if(!"DL00".equals(scrapCode)&&!"HC00".equals(scrapCode)&&!"SY00".equals(scrapCode)){
                            state="SCRAP";
                        }
                        mLotListEntity.setSTATE(state);
                        List<MLotListEntity> list = new ArrayList<>();
                        list.add(mLotListEntity);
                        map.add("MLOTLIST", new JsonParser().parse(new Gson().toJson(list)).getAsJsonArray());
                        map.add("XLOTASSEMBLIES", new JsonParser().parse(new Gson().toJson(list)).getAsJsonArray());
                        NetUtils.requestPostNet("CPC.MLOTKITTING", "MLOTKITTING", this, map, callBack);
                    }
                });
                break;
            case R.id.flMaterielLotList:
                if (materielLotList.size() <= 0){
                    showToast("未获取到物料批次列表",false);
                    return;
                }

                if (gearPop != null) {
                    if (gearPop.isShowing()) {
                        gearPop.dismiss();
                    }
                } else {
                    gearPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMaterielLotList.getWidth(), materielLotList, ivMaterielLotArrow, (codeS, i) -> {
                        tvMaterielLot.setText(codeS);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivMaterielLotArrow);
                gearPop.showAsDropDown(flMaterielLotList, 0, 0);

                break;
            /*case R.id.checkbox:
                System.out.println("#########:"+tvMaterielLot.getText().toString().equals(""));
                if(checkBox.isChecked()){
                    if("".equals(tvMaterielLot.getText().toString())){
                        showToast("请先选择要下机的物料批次!",false);
                       // checkBox.setChecked(false);
                        return;
                    }
                    scapCodeLayout.setVisibility(View.VISIBLE);
                    requestMaterialInfo(tvMaterielLot.getText().toString());
                }else{
                   // scapCodeLayout.setVisibility(View.INVISIBLE);
                  //  System.out.println("spin_scapCode:"+ spin_scapCode.getSelectedItem());

                }
                break;*/
        }

    }
    private void requestMaterialInfo(String mlot){

        FreeUI_EntityCallBack<BaseResponseBean<CpcMaterialInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<CpcMaterialInfoEntity>>
                (new TypeToken<BaseResponseBean<CpcMaterialInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CpcMaterialInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    CpcMaterialInfoEntity.XMLot cpcMaterialInfoEntity = response.body().getResponse().getBody().getXMLot();
                    Map map = (Map) cpcMaterialInfoEntity.getUDF();
                    String materialType = cpcMaterialInfoEntity.getMATERIALTYPE();
                    scrapList=new ArrayList<>();
                    scrapList.add("");
                    if ("REP".equals(materialType)) {
                        scrapList.add("DL00/机台待料下机");
                        scrapList.add("HC00/机台换产下机");
                        scrapList.add("YJ01/装片胶用完");
                        scrapList.add("YJ02/装片胶过期");
                        scrapList.add("YJ03/装片胶分层");
                        scrapList.add("YJ04/装片胶滴胶");
                        scrapList.add("YJ05/装片胶用错");
                        scrapList.add("YJ06/工艺验证");
                    } else if ("WAFER".equals(materialType)) {
                        scrapList.add("SY00/芯片未用完下机");
                      /*  scrapList.add("HC00/机台换产下机");*/
                        scrapList.add("XP01/芯片用完");
                        scrapList.add("XP02/芯片异常");
                       /* scrapList.add("XP03/芯片胶污");
                        scrapList.add("XP04/芯片用错");*/
                        scrapList.add("XP03/工艺验证");
                    } else if ("RLF".equals(materialType)) {
                        scrapList.add("DL00/机台待料下机");
                        scrapList.add("HC00/机台换产下机");
                        scrapList.add("KJ01/框架用完");
                        scrapList.add("KJ02/框架过期");
                        scrapList.add("KJ03/框架变形");
                        scrapList.add("KJ04/框架脏污");
                        scrapList.add("KJ05/框架用错");
                        scrapList.add("KJ06/工艺验证");
                    } else if ("RWR".equals(materialType)) {
                        scrapList.add("SY00/丝材未用完下机");
                       /* scrapList.add("HC00/机台换产下机");*/
                        scrapList.add("SC01/丝材用完");
                        scrapList.add("SC02/丝材过期");
                       /* scrapList.add("SC03/丝材脏污");
                        scrapList.add("SC04/丝材用错");*/
                        scrapList.add("SC03/工艺验证");
                    } else if ("RCM".equals(materialType)) {
                        scrapList.add("DL00/机台待料下机");
                        scrapList.add("HC00/机台换产下机");
                        scrapList.add("SZ01/树脂用完");
                        scrapList.add("SZ02/树脂过期");
                        scrapList.add("SZ03/树脂用错");
                        scrapList.add("SZ04/工艺验证");
                    }
                    else{
                        scrapList.add("DL00/机台待料下机");
                        scrapList.add("SZ01/物料用完");
                    }
                    adapter= new ArrayAdapter<String>(MaterielDownActivity.this,android.R.layout.simple_spinner_item,scrapList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spin_scapCode.setAdapter(adapter);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CpcMaterialInfoEntity>> response) {
                super.onError(response);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("MLOTID",mlot);
        map.addProperty("ACTIONTYPE","QUERYBYID");
        NetUtils.requestPostNet("CPC.FINDMLOTBYID", "TRANSFERMES",this, map, callBack);
    }
}
